﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BugZillaCrawler.UI
{
    public partial class DownloadBugInfo : UserControl
    {
        string _feedUrl = string.Empty;

        public DownloadBugInfo()
        {
            InitializeComponent();
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            StartDownload();
        }

        void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnDownload.Enabled = true;
            lblDownloadStatus.Text = string.Format("Download completed (new: {0})", CSVProcessor.NewBugDownloaded);

            // Refresh UI
            LoadBugList();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                CSVProcessor.DownloadBugList(_feedUrl, chkUpdateExisting.Checked);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtFeedUrl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                StartDownload();
            }
        }

        private void StartDownload()
        {
            if (string.IsNullOrEmpty(txtFeedUrl.Text.Trim()))
            {
                MessageBox.Show("Invalid URL");
            }
            else
            {
                _feedUrl = txtFeedUrl.Text.Trim();
                btnDownload.Enabled = false;

                backgroundWorker.RunWorkerAsync();
                lblDownloadStatus.Text = "Download in progress...";
            }
        }

        private void LoadBugList()
        {
            gridLoader.RunWorkerAsync();
            btnRefresh.Enabled = false;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadBugList();
        }

        private void backgroundWorker_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
        {
            lblDownloadStatus.Text = "";
        }

        List<Bug> _bugDetails = new List<Bug>();
        private void gridLoader_DoWork(object sender, DoWorkEventArgs e)
        {
            _bugDetails = DataAccess.Database.Bugs.ToList<Bug>();
        }

        private void gridLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            grdBugList.DataSource = _bugDetails;
            btnRefresh.Enabled = true;
        }

    }
}
